package com.example.demo.controller;


import com.example.demo.dto.UploadDownloadHistoryDTO;
import com.example.demo.model.*;
import com.example.demo.service.FollowService;
import com.example.demo.service.UserService;
import com.example.demo.service.InviteCodeService;
import com.example.demo.utils.Page;
import com.example.demo.utils.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.net.SocketOption;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/usercenter")
public class UserCenterController {

    public final UserService userService;
    public final InviteCodeService inviteCodeService;
    public final FollowService followService;


    public UserCenterController(UserService userService, InviteCodeService inviteCodeService, FollowService followService) {
        this.userService = userService;
        this.inviteCodeService = inviteCodeService;
        this.followService = followService;
    }

    // 生成邀请码
    @PostMapping("/generate-invite-code")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<?> generateInviteCode() {
        try {
            // 获取当前认证信息
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

            // 直接从认证信息中获取用户ID（推荐方式）
            Long userId = userService.getCurrentUserId(authentication);
            if (userId == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of(
                        "status", "error",
                        "message", "无法获取用户信息"
                ));
            }

            // 生成邀请码
            String code = inviteCodeService.generateInviteCodeForUser(userId);
            return ResponseEntity.ok(Map.of(
                    "status", "success",
                    "code", code
            ));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of(
                    "status", "error",
                    "message", e.getMessage()
            ));
        }
    }

    // 获取用户可用的邀请码
    @GetMapping("/my-invite-codes")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<?> getMyInviteCodes(
            @RequestParam(required = false, defaultValue = "all") String type) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long userId = userService.getCurrentUserId(authentication);

        if (userId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(
                    Map.of("status", "error", "message", "用户未认证"));
        }

        List<InviteCode> codes;
        switch (type.toLowerCase()) {
            case "valid":
                codes = inviteCodeService.getUserValidInviteCodes(userId);
                break;
            case "used":
                codes = inviteCodeService.getUsedInviteCodesByUser(userId);
                break;
            case "all":
            default:
                codes = inviteCodeService.getAllInviteCodesByUser(userId);
                break;
        }

        return ResponseEntity.ok(Map.of(
                "status", "success",
                "type", type,
                "count", codes.size(),
                "codes", codes
        ));
    }

    @PostMapping("/password-forgot-code")
    @ResponseBody
    public Response<String> sendVerificationCode(@RequestBody Map<String, String> registerRequest) {
        String email = registerRequest.get("email");
        try {
            userService.sendVerificationCode(email);
            return Response.success("验证码已发送至邮箱，请注意查收。");
        } catch (Exception e) {
            return Response.fail(Response.INTERNAL_SERVER_ERROR, "验证码发送失败，请稍后再试。");
        }
    }

    @GetMapping("/user-email")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<String> getUserEmail() {
        // 从SecurityContext获取当前认证用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUsername = authentication.getName();

        // 通过用户名查询用户邮箱
        String email = userService.findEmailByUsername(currentUsername);

        return ResponseEntity.ok(email);
    }



    @PostMapping("/new-password")
    @ResponseBody
    public ResponseEntity<?> changePassword(
            @RequestParam("email") String email,
            @RequestParam("code") String code,
            @RequestParam("oldPassword") String oldPassword,
            @RequestParam("newPassword") String newPassword) {

        try {

            //获取用户（假设UserService中有根据email获取用户的方法）
            User user = userService.findByEmail(email);
            if (user == null) {
                return ResponseEntity.badRequest().body(Map.of(
                        "status", "error",
                        "message", "用户不存在"
                ));
            }

            //调用服务层方法
            userService.changePassword(user, code, oldPassword, newPassword);

            return ResponseEntity.ok().body(Map.of(
                    "status", "success",
                    "message", "密码修改成功"
            ));

        } catch (RuntimeException e) {
            // 捕获服务层抛出的验证码错误、密码错误等异常
            return ResponseEntity.badRequest().body(Map.of(
                    "status", "error",
                    "message", e.getMessage() != null ? e.getMessage() : "未知错误"
            ));
        } catch (Exception e) {
            log.error("密码修改失败", e);
            return ResponseEntity.badRequest().body(Map.of(
                    "status", "error",
                    "message", "密码修改失败"
            ));
        }
    }

    @GetMapping("/balance")
//    @PreAuthorize("hasRole('USER')")
    public Response<Map<String, Object>> getBalance() {
        Long currentUserId = getCurrentUserId();
        return Response.success(userService.getUserBalance(currentUserId));
    }

    private Long getCurrentUserId() {
        return ((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId();
    }

    @GetMapping("/notices")
    public ResponseEntity<List<Notice>> getPublicNotices() {
        try {
            List<Notice> notices = userService.getAllNotices();
            return ResponseEntity.ok(notices);
        } catch (Exception e) {
            log.error("获取公共通知失败", e);
            return ResponseEntity.status(500).body(null);
        }
    }

    @PostMapping("/username")
    public ResponseEntity<?> changeUserName(@RequestParam Long id, @RequestParam String username){
        try {
            System.out.println("username change\n"+id + username);
            userService.updateUserName(id, username);
            return ResponseEntity.ok().body(Map.of(
                    "status", "success",
                    "message", "用户名修改成功"
            ));
        }catch (Exception e){
            return ResponseEntity.badRequest().body(Map.of(
                    "status", "error",
                    "message", "用户名修改失败"
            ));
        }
    }

    @GetMapping("/uploads")
    @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    public ResponseEntity<List<UploadDownloadHistoryDTO>> getUploadHistory(@RequestParam Long userId) {
        try {
            List<UploadDownloadHistoryDTO> uploads = userService.getUploadHistory(userId);
            if (uploads.isEmpty()) {
                return ResponseEntity.noContent().build();
            }
            return ResponseEntity.ok(uploads);
        } catch (Exception e) {
            log.error("查询用户 {} 的上传历史失败", userId, e);
            return ResponseEntity.status(500).body(null);
        }
    }

    @GetMapping("/downloads")
    @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    public ResponseEntity<List<UploadDownloadHistoryDTO>> getDownloadHistory(@RequestParam Long userId) {
        try {
            List<UploadDownloadHistoryDTO> downloads = userService.getDownloadHistory(userId);
            if (downloads.isEmpty()) {
                return ResponseEntity.noContent().build();
            }
            return ResponseEntity.ok(downloads);
        } catch (Exception e) {
            log.error("查询用户 {} 的下载历史失败", userId, e);
            return ResponseEntity.status(500).body(null);
        }
    }

    @PostMapping("/follow")
    @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    public ResponseEntity<?> toggleFollowUser(@RequestBody Map<String, Object> params) {
        Long userId = Long.valueOf(params.get("userId").toString());
        Long targetUserId = Long.valueOf(params.get("targetUserId").toString());
        String action = params.get("action").toString();

        try {
            if ("follow".equalsIgnoreCase(action)) {
                followService.follow(userId, targetUserId);
                return ResponseEntity.ok(Map.of(
                        "status", "success",
                        "message", "关注成功"
                ));
            } else if ("unfollow".equalsIgnoreCase(action)) {
                followService.unfollow(userId, targetUserId);
                return ResponseEntity.ok(Map.of(
                        "status", "success",
                        "message", "取消关注成功"
                ));
            } else {
                return ResponseEntity.badRequest().body(Map.of(
                        "status", "error",
                        "message", "未知操作"
                ));
            }
        } catch (Exception e) {
            log.error("关注/取消关注用户失败", e);
            return ResponseEntity.status(500).body(Map.of(
                    "status", "error",
                    "message", "操作失败"
            ));
        }
    }

    @GetMapping("/followed")
    @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    public ResponseEntity<List<Follow>> getFollowedUsers(@RequestParam Long userId) {
        try {
            List<Follow> followedUsers = followService.getFollowings(userId);
            if (followedUsers.isEmpty()) {
                return ResponseEntity.noContent().build();
            }
            return ResponseEntity.ok(followedUsers);
        } catch (Exception e) {
            log.error("获取关注的用户列表失败", e);
            return ResponseEntity.status(500).body(null);
        }
    }

    @GetMapping("/followers")
    @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    public ResponseEntity<List<Follow>> getFollowers(@RequestParam Long userId) {
        try {
            List<Follow> followers = followService.getFollowers(userId);
            if (followers.isEmpty()) {
                return ResponseEntity.noContent().build();
            }
            return ResponseEntity.ok(followers);
        } catch (Exception e) {
            log.error("获取粉丝列表失败", e);
            return ResponseEntity.status(500).body(null);
        }
    }

}
